package org.yang.loginunion.core.email;

import com.alipay.api.domain.EcoRenthouseOtherAmount;
import org.apache.commons.lang3.StringUtils;
import org.yang.loginunion.core.LoginClient;
import org.yang.loginunion.core.constants.IdentityType;
import org.yang.loginunion.core.exception.LoginException;
import org.yang.loginunion.core.model.BindAuthCode;
import org.yang.loginunion.core.repository.OauthRepository;
import org.yang.loginunion.core.repository.OauthTempRepository;
import org.yang.loginunion.core.repository.VerifycodeRepository;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.locks.Lock;

/**
 * 邮箱+验证码登录（并绑定第三方登录信息）
 *
 * <pre>
 * 使用场景：微信APP、微信公众号登录过程中需要绑定邮箱，以邮箱作为系统用户必须的登录方式（如果是以手机号作为必须的登录方式，逻辑类似）
 * </pre>
 *
 * @author Billyang
 * @date 2024/8/3 16:14
 */
public class EmailCodeBindClient implements LoginClient {

    private OauthRepository oauthRepository;

    private OauthTempRepository oauthTempRepository;

    private VerifycodeRepository verifycodeRepository;

    public EmailCodeBindClient(OauthRepository oauthRepository, OauthTempRepository oauthTempRepository, VerifycodeRepository verifycodeRepository) {
        this.oauthRepository = oauthRepository;
        this.oauthTempRepository = oauthTempRepository;
        this.verifycodeRepository = verifycodeRepository;
    }

    @Override
    public String login(String email, String code, String bindCode) {
        if (StringUtils.isAnyBlank(email, code)) {
            throw new LoginException("缺失参数");
        }
        //核对验证码
        boolean checkVerifycode = verifycodeRepository.checkVerifycode(email, code);
        if (!checkVerifycode) {
            throw new LoginException("验证码错误");
        }

        String userId = oauthRepository.getUserId(IdentityType.EMAIL, email);
        //获取绑定邮箱或手机号等信息
        BindAuthCode bindAuthCode = oauthTempRepository.getBindAuthCode(bindCode);

        if (userId == null) {
            // 创建新用户
            String nickname = Optional.ofNullable(bindAuthCode).map(BindAuthCode::getNickname).orElse(null);
            String avator = Optional.ofNullable(bindAuthCode).map(BindAuthCode::getHeadimgurl).orElse(null);

            userId = oauthRepository.registerUser(IdentityType.EMAIL, email, nickname, avator);
        }

        // 绑定authcode
        if (bindAuthCode != null) {
            List<BindAuthCode.BindUserOauth> binds = bindAuthCode.getBinds();
            for (BindAuthCode.BindUserOauth bind : binds) {
                String identifier = bind.getIdentifier();
                if (StringUtils.isNotBlank(identifier)) {
                    oauthRepository.bindOauth(userId, bind.getIdentityType(), identifier, bindCode);
                }
            }
        }
        return userId;
    }
}
